package cn.xyz.mianshi.currency;

import cn.xyz.commons.constants.KConstants;
import cn.xyz.commons.ex.ServiceException;
import cn.xyz.commons.support.mongo.MongoOperator;
import cn.xyz.commons.utils.DateUtil;
import cn.xyz.commons.utils.StringUtil;
import cn.xyz.mianshi.model.PageResult;
import cn.xyz.mianshi.utils.SKBeanUtils;
import cn.xyz.mianshi.vo.DigitalConvertRecord;
import cn.xyz.mianshi.vo.DigitalCurrency;
import cn.xyz.mianshi.vo.DigitalLink;
import cn.xyz.mianshi.vo.DigitalSymbol;
import cn.xyz.repository.mongo.MongoRepository;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.query.Query;
import org.mongodb.morphia.query.UpdateOperations;
import org.springframework.stereotype.Service;
import sun.rmi.runtime.Log;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class DigitalSymbolManagelmpl extends MongoRepository<DigitalSymbol, ObjectId> {
    @Override
    public Datastore getDatastore() {
        return SKBeanUtils.getDatastore();
    }

    @Override
    public Class<DigitalSymbol> getEntityClass() {
        return DigitalSymbol.class;
    }

    /**
     * 添加新链地址
     * @param Symbol
     * @param address
     * @param UserID
     */
    public void addDigitalSymbolInfo(String Symbol,String address,int UserID)
    {
        DigitalLink query = SKBeanUtils.getDatastore().createQuery(DigitalLink.class).field("userId").equal(UserID).field("Symbol").equal(Symbol).get();
        if(query == null)
        {
            DigitalLink _data = new DigitalLink();
            _data.setAddress(address);
            _data.setSymbol(Symbol);
            _data.setUserId(UserID);
            SKBeanUtils.getDatastore().save(_data);
        }
    }
    public  void addDigitalSymbolBalance(String Symbol,String address,int UserID)
    {
        DigitalSymbol query = SKBeanUtils.getDatastore().createQuery(DigitalSymbol.class).field("userId").equal(UserID).field("Symbol").equal(Symbol).get();
        if(query == null){
            DigitalSymbol _data = new DigitalSymbol();
            _data.setUserId(UserID);
            _data.setAddress(address);
            _data.setSymbol(Symbol);
            _data.setBalance(0);
            SKBeanUtils.getDatastore().save(_data);
        }
    }

    /**
     * 查询数字货币地址
     * @param Symbol
     * @param UserID
     * @return
     */
    public String getDigitalSymbolInfo(String Symbol,int UserID) {
        DigitalLink query = SKBeanUtils.getDatastore().createQuery(DigitalLink.class).field("userId").equal(UserID).field("Symbol").equal(Symbol).get();
        if (query == null) return null;
        return query.getAddress();
    }
    /**
     * 更新金额
     * @param Symbol
     * @param balance
     * @param UserID
     */
    public boolean rechargeBalance(String Symbol,Double balance,int UserID,int type)
    {
        if(Symbol.equals("yestalk"))
        {
            if( balance<0){
                throw new ServiceException(KConstants.PayResultCode.InsufficientBalance);
            }
            SKBeanUtils.getUserManager().rechargeUserMoeny(UserID,balance,type);
            return true;
        }
        DigitalSymbol query = SKBeanUtils.getDatastore().createQuery(DigitalSymbol.class).field("userId").equal(UserID).field("Symbol").equal(Symbol).get();
        if(query == null){
            return false;
        }
        double dbBalance = query.getBalance();
        double newBalance=0.0;
        if(KConstants.MOENY_ADD==type)
        {
            newBalance= StringUtil.addDouble(dbBalance, balance);
        }
        else{
            newBalance= StringUtil.subDouble(dbBalance, balance);
        }
        UpdateOperations<DigitalSymbol> ops=getDatastore().createUpdateOperations(DigitalSymbol.class);
        ops.set("balance",newBalance);
        Query<DigitalSymbol> q =getDatastore().createQuery(getEntityClass());
        q.field("userId").equal(UserID);
        q.field("Symbol").equal(Symbol);
        getDatastore().update(q, ops);
        return true;
    }
    public  Double getUserMoeny(int UserID,String Symbol)
    {
        if(Symbol.equals("yestalk"))
        {
            return SKBeanUtils.getUserManager().getUserMoeny(UserID);
        }
        else{
            DigitalSymbol query = SKBeanUtils.getDatastore().createQuery(DigitalSymbol.class).field("userId").equal(UserID).field("Symbol").equal(Symbol).get();
            if(query == null) return 0.0;
            return query.getBalance();
        }
    }
    public Double getConvertRate(String Symbol)
    {
        if(Symbol.equals("yestalk")){
            return 1.0;
        }
        else{
            Double dbSrcToUpayRate = 0.0;
            DigitalCurrency query = SKBeanUtils.getDatastore().createQuery(DigitalCurrency.class).field("queryName").equal(Symbol).get();
            if(query != null)
            {
                dbSrcToUpayRate = Double.parseDouble(query.getConvertRate2()) ;
            }
            return dbSrcToUpayRate;
        }
    }
    /**
     * 数字货币转换
     * @param UserID
     * @param srcSymbol
     * @param tagSymbol
     * @return
     */
    public  boolean onDigitalConvert(int UserID,String srcSymbol,String tagSymbol,Double dbScore)
    {
        //查询货币A对法币的汇率
        Double dbSrcToUpayRate =  SKBeanUtils.getDigitalCurrencyManager().getDigitalRate(srcSymbol);

        Double dbTagToUpayRate =  SKBeanUtils.getDigitalCurrencyManager().getDigitalRate(tagSymbol);

        Double dbsrcSymbolScore =getUserMoeny(UserID,srcSymbol);


        if(dbsrcSymbolScore < dbScore) return false;
        logger.info("[ww]:dbsrcSymbolScore="+dbsrcSymbolScore+",dbScore="+dbScore);
        //先转换为法币
        Double  convertScore =  dbScore * dbSrcToUpayRate;
        //法币转为对应类型
        convertScore = convertScore /dbTagToUpayRate;
        convertScore = (double) Math.round(convertScore* 1000)/1000;
        if(tagSymbol.equals("yestalk"))
        {
            convertScore = (double) Math.round(convertScore* 100)/100;
        }
        rechargeBalance(srcSymbol,dbScore,UserID,KConstants.MOENY_REDUCE);
        if(!rechargeBalance(tagSymbol,convertScore,UserID,KConstants.MOENY_ADD))
        {
            rechargeBalance(srcSymbol,dbScore,UserID,KConstants.MOENY_ADD);
            return false;
        }


        //写记录
        DigitalConvertRecord _data = new DigitalConvertRecord();
        _data.setUserID(UserID);
        _data.setConvertValue(dbScore);
        _data.setTagValue(convertScore);
        _data.setSrcSymbol(srcSymbol);
        _data.setTagSymbol(tagSymbol);
        _data.setConvertTime(DateUtil.currentTimeSeconds());
        SKBeanUtils.getDatastore().save(_data);

        return  true;
    }

    /**
     * 转换记录
     * @param userId
     * @param page
     * @param limit
     * @param srcSymbol
     * @param tagSymbol
     * @param startTimes
     * @param endTimes
     * @return
     */
    public PageResult<DBObject> getDigitalConvertRecord(Integer userId,int page,int limit,String srcSymbol,String tagSymbol,int startTimes,int endTimes)
    {
        PageResult<DBObject>  result = new PageResult<DBObject>();
        List<DBObject> convertRecords = new ArrayList<>();
        final DBCollection collection = SKBeanUtils.getDatastore().getDB().getCollection("digitalConvertRecord");
        BasicDBObject basicDBObject = new BasicDBObject("UserID",userId);
        if(startTimes>0)
        {
            basicDBObject.append("convertTime", new BasicDBObject(MongoOperator.GT,startTimes));
        }
        if(endTimes>0)
        {
            basicDBObject.append("convertTime", new BasicDBObject(MongoOperator.LT,endTimes));
        }

        if(!StringUtil.isEmpty(srcSymbol))
        {
            basicDBObject.append("srcSymbol",srcSymbol );
        }
        if(!StringUtil.isEmpty(tagSymbol))
        {
            basicDBObject.append("tagSymbol",tagSymbol );
        }
        page = page > 0 ? page - 1 : 0;
        limit = limit > 0 ?limit : 20;
        DBCursor dbCursor = getDatastore().getDB().getCollection("digitalConvertRecord").find(basicDBObject).sort(new BasicDBObject("convertTime",-1))
                .skip((page)*limit).limit(limit);

        while (dbCursor.hasNext()) {
            DBObject obj = dbCursor.next();
            convertRecords.add(obj);
        }
        result.setCount(dbCursor.count());
        result.setData(convertRecords);
        return result;
    }

    public int getUserIDForAdder(String Symbol,String address)
    {
        DigitalSymbol query = SKBeanUtils.getDatastore().createQuery(DigitalSymbol.class).field("address").equal(address).field("Symbol").equal(Symbol).get();
        if(query == null) return 0;
        return query.getUserId();
    }
}
